package com.tramp.frame.server.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.tramp.frame.server.thread.ThreadInitCenter;

/**
 * Created by chen on 2017/10/22.
 */
public class TrampInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		request.setAttribute("basePath", getAbsolutelypath(request));
		//线程开始前初始化
		ThreadInitCenter.init(request);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
			throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
			throws Exception {
		ThreadInitCenter.end();
	}

	private String getAbsolutelypath(HttpServletRequest request) {
		String absoluteContextPath;
		String portocol = "";
		if (request.isSecure()) {
			portocol = "https://";
		}
		else {
			portocol = "http://";
		}
		absoluteContextPath = portocol + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
		return absoluteContextPath;
	}
}
